<template>
  <section class='f-order' :style="{height: currentHeight}">
    <div>
      <section class="f-title">
        <van-tabs v-model:active="searchForm.queryType" style="flex:1" color="#ffffff" background="#000000"
          title-active-color="#ffffff" title-inactive-color="#D8D8D8" @click-tab="clickTab">
          <van-tab title="直接订单" :name="1"></van-tab>
          <van-tab title="下游订单" :name="2"></van-tab>
        </van-tabs>
      </section>

      <ul class="f-search f-mt-05">
        <li class="g-flex-ct" @click="openDatePicker()">
          <p class="f-mr-05">{{currentDateStr}}</p>
          <van-icon style="margin-top:2px" name="arrow-down" />
        </li>
        <li v-if="searchForm.queryType == 2" class="g-flex-ct" @click="openPicker(1)">
          <p class="f-mr-05">{{searchForm.shopIName || '全部代理商'}}</p>
          <van-icon style="margin-top:2px" name="arrow-down" />
        </li>
      </ul>
      <ul class="f-search f-mt-10">
        <li class="g-flex-ct" @click="openPicker(2)">
          <p class="f-mr-05">{{searchForm.orderStatusName || '订单状态'}}</p>
          <van-icon style="margin-top:2px" name="arrow-down" />
        </li>
        <li class="g-flex-ct" @click="openPicker(3)">
          <p class="f-mr-05">{{searchForm.activeStatusName || '激活状态'}}</p>
          <van-icon style="margin-top:2px" name="arrow-down" />
        </li>
        <li class="g-flex-ct" @click="openPicker(4)">
          <p class="f-mr-05">{{searchForm.goodsName || '全部商品'}}</p>
          <van-icon style="margin-top:2px" name="arrow-down" />
        </li>
      </ul>
    </div>

    <van-pull-refresh v-model="refreshing" @refresh="onRefresh" style="overflow-y: auto;flex:1;">
      <van-list v-model:loading="loading" :finished="finished" finished-text="没有更多了" @load="onLoad">
        <section class="f-cell-group" v-for="(item,index) in tableData" :key="index">
          <section class="f-cell">
            <div v-if="searchForm.queryType == 2" class="f-agency">
              {{item.fromShopName || '--'}}
              <p class="f-agency-divider"></p>
            </div>
            <section class="f-content" @click="pageJump(item)">
              <div class="f-flex-between">
                <div class="g-flex-ct">
                  <p style="color: #666666;">订单编号：</p>
                  <p>{{item.sysOrderId}}</p>
                </div>
                <p>{{ getDateTime(item.createTime)[6] }}</p>
              </div>

              <div class="f-content-text">
                <img style="width:35px;height:35px" src="@/assets/icons/jhh_icon_datum.png" alt="">
                <ul>
                  <li style="width:100%">
                    <p>商品名称：</p>
                    <p>{{item.goodsName}}</p>
                  </li>
                  <li>
                    <p>售卡号码：</p>
                    <p>{{item.goodsPhone || '--'}}</p>
                  </li>

                  <li>
                    <p>商品预存：</p>
                    <p>{{item.prestoreShow}}元</p>
                  </li>

                  <li>
                    <p>订单状态：</p>
                    <p :style="{'color': orderStatusColor[item.orderStatus]}">{{orderStatus[item.orderStatus]}}</p>
                  </li>
                  <li>
                    <p>激活状态：</p>
                    <p>{{activeStatus[item.activeStatus]}}</p>
                  </li>
                  <li>
                    <p>开卡人：</p>
                    <p>{{item.idcardName}}</p>
                  </li>
                </ul>
              </div>

            </section>
            <p v-if="index+1 < tableData.length" class="f-divider"></p>
          </section>
        </section>
      </van-list>
    </van-pull-refresh>

    <van-popup v-model:show="showPicker" closeable position="bottom" close-icon-position="top-left">
      <p class="f-popup-title">选择{{pickerTitle}}</p>
      <van-picker ref="pickerRef" v-model="selectId" :columns="columns" :columns-field-names="customFieldName"
        :show-toolbar="false" />

      <div class="f-popup-btn">
        <van-button block type="primary" @click="handlePicker()">确定</van-button>
      </div>
    </van-popup>

    <Date-Picker ref="datePickerRef" type="time" @selectDate="selectDate"></Date-Picker>
  </section>
</template>
<script>
import { ref, reactive, toRefs, onMounted, computed, watch, onActivated } from 'vue';
import { useRouter, useRoute } from 'vue-router'
import { useStore } from 'vuex';
import { toThousands, getUnixTime, initDatepicker, getDateTime } from '@/utils/utils';
import DatePicker from '@/components/DatePicker.vue'
import api from './api'

export default {
  name: 'orderList',

  components: { DatePicker },

  setup(props, context) {
    const store = useStore()

    const router = useRouter()
    const route = useRoute();

    const pickerRef = ref()
    const datePickerRef = ref()

    const state = reactive({
      searchForm: {
        queryType: 1,

        "activeStatus": "",
        "createTimeMax": "",
        "createTimeMin": "",
        "goodsId": "",
        "goodsPhone": "",
        "idcardName": "",
        "idcardNum": "",
        "operator": "",
        "orderBy": "id desc",
        "orderStatus": "",
        "page": 1,
        "receivePhone": "",
        "receiverName": "",
        "refundStatus": "",
        "shopId": "",
        "size": 10,
        "submitType": "",
        "sysOrderId": ""
      },
      selectId: [],

      currentDateStr: "",

      loading: false,
      finished: false,
      refreshing: false,
      tableData: [],
      total: 0,
      currentHeight: '740px',

      pickerTitle: '',
      showPicker: false,
      columns: [],
      customFieldName: {
        text: 'text',
        value: 'value',
        children: 'children'
      },

      orderStatus: {
        '5': "待支付",
        '10': "订单进行中",
        '20': "受理成功",
        '30': "订单异常结束",
        '40': "订单异常待处理",
        '50': "超时关闭",
      },
      orderStatusColor: {
        '5': "#E6A23C",
        '10': "#409EFF",
        '20': "#67C23A",
        '30': "#F56C6C",
        '40': "#F56C6C",
        '50': "#F56C6C",
      },

      activeStatus: {
        '0': '未激活',
        '10': '已下单',
        '12': '激活中',
        '14': '下单失败',
        '20': '激活成功',
        '22': '充值成功',
        '30': '激活失败',
      },

      goodsList: [],
      consumerList: [],

      orderId: computed(() => {
        return store.state.orderId;
      }),
    })

    watch(() => state.orderId, (newVal, oldVal) => {
      state.searchForm.sysOrderId = state.orderId
      state.refreshing = true
      onRefresh()
    })

    onActivated(() => {
      store.commit("setNavBar", {
        title: '我的订单',
        show: true,
        left: false,
        leftType: 'back',
        right: true,
        rightType: 'search',
      });
    })

    onMounted(() => {
      store.commit("setNavBar", {
        title: '我的订单',
        show: true,
        left: false,
        leftType: 'back',
        right: true,
        rightType: 'search',
      });

      state.currentHeight = window.innerHeight - 80 + 'px'

      state.searchForm.createTimeMin = initDatepicker(4, 3 * 30 * 24 * 60 * 60 * 1000);
      state.searchForm.createTimeMax = initDatepicker(3);
      let str = getDateTime(state.searchForm.createTimeMin)[8] + ' 至 ' + getDateTime(state.searchForm.createTimeMax)[8]
      state.currentDateStr = str

      getGoodsChooseList()
      getConsumerList()
    })

    const getGoodsChooseList = () => {
      api.goodsChooseList({ shelveStatus: 1 }).then(res => {
        state.goodsList = res.data.list
      })
    }

    const getConsumerList = () => {
      api.consumerList().then(res => {
        state.consumerList = res.data.list
      })
    }

    const onLoad = () => {
      let json = JSON.parse(JSON.stringify(state.searchForm))

      if (state.refreshing) {
        state.tableData = [];
        state.refreshing = false;
      }

      let apiName = state.searchForm.queryType == 1 ? 'orderQryList' : 'orderPromotionList'
      api[apiName](json).then(res => {
        state.refreshing = false

        if (res.data.list.length) state.searchForm.page += 1
        state.tableData.push(...res.data.list)

        // 防止触发两次
        if (state.tableData.length >= res.data.total) {
          state.finished = true;
        } else {
          state.finished = false;
        }

        // 加载状态结束
        state.loading = false;

        // 数据全部加载完成
        if (state.tableData.length < 10) {
          state.finished = true;
        }
      }).catch(err => {
        state.loading = false;
        state.finished = true;
        state.refreshing = false
      })
    };

    const onRefresh = () => {
      state.searchForm.page = 1

      // 清空列表数据
      state.finished = false;

      // 重新加载数据
      // 将 loading 设置为 true，表示处于加载状态
      state.loading = true;
      onLoad();
    };

    const openDatePicker = () => {
      datePickerRef.value.datePopup = true
    }

    const selectDate = (e) => {
      let str = e.startStr + ' 至 ' + e.endStr
      state.currentDateStr = str
      state.searchForm.createTimeMin = getUnixTime(e.startStr)
      state.searchForm.createTimeMax = getUnixTime(e.endStr) - 999 + 24 * 60 * 60 * 1000;
      state.refreshing = true
      onRefresh()
    }

    const openPicker = (e) => {
      if (e == 2) {
        state.pickerTitle = '订单状态'
        state.columns = [
          { text: '全部', value: '' },
          { text: '待支付', value: '5' },
          { text: '订单进行中', value: '10' },
          { text: '受理成功', value: '20' },
          { text: '订单异常结束', value: '30' },
          { text: '订单异常待处理', value: '40' },
        ]
      } else if (e == 3) {
        state.pickerTitle = '激活状态'
        state.columns = [
          { text: '全部', value: '' },
          { text: '未激活', value: '0' },
          { text: '已下单', value: '10' },
          { text: '激活中', value: '12' },
          { text: '下单失败', value: '14' },
          { text: '激活成功', value: '20' },
          { text: '充值成功', value: '22' },
          { text: '激活失败', value: '30' },
        ]
      } else if (e == 4) {
        state.pickerTitle = '全部商品'

        let list = [
          { text: '全部', value: '' },
        ]
        state.goodsList.forEach(item => {
          let obj = { text: item.goodsName, value: item.goodsId }
          list.push(obj)
        })
        state.columns = list
      } else if (e == 1) {
        state.pickerTitle = '全部代理商'

        let list = [
          { text: '全部', value: '' },
        ]
        state.consumerList.forEach(item => {
          let obj = { text: item.shopName, value: item.shopId }
          list.push(obj)
        })
        state.columns = list
      }
      state.showPicker = true
    }

    const handlePicker = (e) => {
      let data = pickerRef.value.confirm().selectedOptions[0]
      state.showPicker = false
      state.refreshing = true
      if (state.pickerTitle == '订单状态') {
        state.searchForm.orderStatus = data.value
        state.searchForm.orderStatusName = data.text == '全部' ? '' : data.text
      }
      if (state.pickerTitle == '激活状态') {
        state.searchForm.activeStatus = data.value
        state.searchForm.activeStatusName = data.text == '全部' ? '' : data.text
      }
      if (state.pickerTitle == '全部商品') {
        state.searchForm.goodsId = data.value
        state.searchForm.goodsName = data.text == '全部' ? '' : data.text
      }
      if (state.pickerTitle == '全部代理商') {
        state.searchForm.shopId = data.value
        state.searchForm.shopIName = data.text == '全部' ? '' : data.text
      }

      onRefresh()
    }

    const clickTab = (e) => {
      if (e.name == 1) {
        state.searchForm.queryType = 1
        state.searchForm.shopId = ""
        state.searchForm.shopIName = ""
      } else {
        state.searchForm.queryType = 2
      }
      state.searchForm.sysOrderId = ""

      state.refreshing = true
      onRefresh()
    }

    const pageJump = (params) => {
      router.push({
        path: '/order/detail',
        query: {
          sysOrderId: params.sysOrderId,
          queryType: state.searchForm.queryType,
        }
      })

      addCacheRoute()
    }

    const addCacheRoute = () => {
      store.commit("addCacheRoute", 'orderList');
    }

    return {
      ...toRefs(state),
      pickerRef,
      datePickerRef,
      getDateTime,
      toThousands,
      onLoad,
      onRefresh,
      openDatePicker,
      selectDate,
      openPicker,
      handlePicker,
      clickTab,
      pageJump
    }
  }
}
</script>
<style lang='scss' scoped>
.f-order {
  display: flex;
  flex-direction: column;
  .f-title {
    background: #000000;
    display: flex;
    align-items: center;
    padding-bottom: 8px;
  }
  .f-date {
    font-weight: 300;
    font-size: 12px;
    color: #000000;
    padding: 11px 15px 10px 17px;
  }
  .f-search {
    font-size: 12px;
    font-weight: 300;
    color: #000000;
    padding: 0px 15px 6px 17px;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .f-cell-group {
    background: #ffffff;
    .f-cell {
      .f-content {
        padding: 13px 14px 7px 17px;
        .f-content-text {
          margin-top: 12px;
          display: flex;
          align-items: center;
          line-height: 16px;
          font-size: 10px;
          ul {
            display: flex;
            align-items: center;
            flex-wrap: wrap;
            li {
              display: flex;
              align-items: center;
              width: 50%;
              margin: 2px 0;
            }
            p:first-child {
              color: #666666;
              width: 70px;
              text-align: right;
            }
          }
        }
      }
      .f-divider {
        width: 100%;
        height: 1px;
        border-bottom: 1px solid #dddddd;
      }
      .f-agency {
        padding: 8px 0 0px 17px;
        .f-agency-divider {
          margin-top: 8px;
          width: 100%;
          height: 1px;
          border-bottom: 1px dashed #dddddd;
        }
      }
    }
  }
}
</style>